﻿using System;
using System.Collections;
using System.Reflection;
namespace CommandLib
{
    /// <summary>
    /// 自定义控制反转
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    public abstract class AssesUtil<T> where T : class,new()
    {
        /// <summary>
        /// 缓存集合
        /// </summary>
        private static readonly Hashtable hash = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// 执行实例方法
        /// </summary>
        /// <param name="FunName">方法名</param>
        /// <param name="type">参数类型</param>
        /// <param name="arg">参数实体</param>
        /// <returns></returns>
        public static object Invoke(string FunName, Type[] type, params object[] arg)
        {
            object result = null;
            try
            {
                Type types = typeof(T);
                var classname =types.FullName;
                MethodInfo method = types.GetMethod(FunName, type);
                if (hash[classname] != null)
                {
                    result = method.Invoke(hash[classname], arg);
                }
                else
                {
                    var func = Activator.CreateInstance(types);
                    result = method.Invoke(func, arg);
                    hash[classname] = func;
                }

            }
            catch (Exception)
            {
                throw;
            }

            return result;

        }
        
        /// <summary>
        /// 获取单个类实列
        /// </summary>
        /// <returns></returns>
        public static T GetInstance() 
        {
            T result = default(T);
            try
            {
                //获得泛型类的对象类型
                Type type = typeof(T);
                var classname = type.FullName;
                if (hash[classname] != null)
                {
                    result = hash[classname] as T;
                }
                else
                {   //根据对象的类型创建对象的实例
                    result = Activator.CreateInstance(type) as T;
                    hash[classname] = result;
                }

            }
            catch (Exception )
            {
                throw;
            }
            return result;
        }
    }
}
